package com.aaa.hospital.controller;

import com.aaa.hospital.pojo.domain.Dept;
import com.aaa.hospital.pojo.query.DeptQuery;
import com.aaa.hospital.result.AjaxResult;
import com.aaa.hospital.service.DeptService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author: HJT
 * @DateTime: 2022/2/23 9:03
 * @Description: TODO
 */
@Controller
@RequestMapping("deptsource")
public class DeptSourceController {
    @Autowired
    private DeptService deptService;


    @RequestMapping("upload")
    public AjaxResult uploadExcel(MultipartFile hehe) throws  Exception{
        byte[] bytes = hehe.getBytes();
        long size = hehe.getSize();
        String name = hehe.getName();
        String originalFilename = hehe.getOriginalFilename();
        String contentType = hehe.getContentType();
        InputStream inputStream = hehe.getInputStream();

        ExcelReaderBuilder read = EasyExcel.read(hehe.getInputStream(), Dept.class,null);
        List<Dept> objects = read.doReadAllSync();
        Integer a =0;
        for (Dept object : objects) {
            AjaxResult ajaxResult = deptService.addDept(object);
            if (ajaxResult.getCode()==1){
                a++;
            }
        }
        if (a>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.fail();
        }
    }











    @RequestMapping("download")
    public void download(DeptQuery query, HttpServletResponse response) throws Exception{
        AjaxResult ajaxResult = deptService.queryDept(query);
        Map map =(Map) ajaxResult.getData();
        List<Dept> currentData = (List<Dept>) map.get("currentData");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("部门信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");


        EasyExcel.write(   response.getOutputStream()  , Dept.class    )     .sheet("部门信息").doWrite( currentData );
    }
}
